import { type varType } from "./base";

export default class Comments {

    vars: varType[] = []
    paran_vars: varType[] = []

    constructor(node: Array<any>, paran_vars: varType[]) {
        this.paran_vars = paran_vars
        for (const item of node) {
            this.getCode(item.value)
        }
    }

    private checkVar(arr1: varType[], arr2: varType[]) {
        // 使用 Map 存储序列化的对象（性能优化）
        const seen = new Map<string, varType>();
        const duplicates: varType[] = [];

        // 序列化函数（确保属性顺序一致）
        const serialize = (obj: varType): string => {
            const sortedKeys = Object.keys(obj).sort();
            const normalizedObj: Record<string, any> = {};
            sortedKeys.forEach(key => {
                normalizedObj[key] = obj[key];
            });
            return JSON.stringify(normalizedObj);
        };

        // 处理第一个数组
        arr1.forEach(item => {
            seen.set(serialize(item), item);
        });

        // 比较第二个数组
        arr2.forEach(item => {
            const key = serialize(item);
            if (seen.has(key)) {
                duplicates.push(seen.get(key)!);
                seen.delete(key); // 防止重复报告
            }
        });

        return duplicates;
    }

    private getCode(str: string): void {
        // 换行符 \r\n 分割为数组
        const arr = str.split(/\r\n/)
        for (const item of arr) {
            const variable = item.replace("/**", "").replace("*/", "").replace("*", "").replace("//", "").trim()
            if (variable.startsWith("@var ")) {
                const var_arr: string[] = variable.replace("@var ", "").split(" ")
                // 为了避免将 undefined 赋值给 string 类型，添加默认值空字符串
                // 为确保 name 为 string 类型，添加三元表达式处理可能的 undefined 情况
                const varType0: string = var_arr[0] as string;
                const varName: string = var_arr[1] ? var_arr[1].replace('$', '') : '';
                this.vars.push({ type: varType0, var: varName });
            }
        }
    }

    public value(): varType[] {
        return this.vars
    }
}